package com.huaxin.hxcloud.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.SearchDTO;
import com.huaxin.common.Entity.StationDTO;
import com.huaxin.common.Entity.VehicleDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.Log;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.RoundLayout;
import com.huaxin.common.view.StaticSearchBar;
import com.huaxin.common.view.pulltorefresh.CustomFooterLayout;
import com.huaxin.common.view.pulltorefresh.CustomHeaderLayout;
import com.huaxin.common.view.pulltorefresh.PullToRefreshBase;
import com.huaxin.common.view.pulltorefresh.extras.recyclerview.PullToRefreshRecyclerView;
import com.huaxin.hxcloud.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindColor;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/10/28.
 */

public class CommonSearchActivity extends BaseActivity implements PullToRefreshBase
        .OnRefreshListener2 {


    @BindView(R.id.pull_view)
    PullToRefreshRecyclerView pullView;
    @BindView(R.id.editView)
    EditText                  editView;
    @BindView(R.id.delete)
    ImageView                 delete;
    @BindView(R.id.search)
    TextView                  search;
    @BindView(R.id.toolbar)
    StaticSearchBar           toolbar;

    int          searchType;
    String       searchTypeName;
    RecyclerView listView;
    MyAdapter    myAdapter;
    public final static int MODE_DEFAULT        = 0x00;
    public final static int MODE_SEARCH_STATION = 0x01;
    public final static int MODE_SEARCH_PLATE   = 0x02;
    private             int _mPageNo            = 0;
    List datas = new ArrayList<>();
    private int    _pageSize = 1;
    private String _keyword  = "";
    private PopupWindow popupWindow;
    private int         _extraId;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_common_search;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    public static void start(Activity context, int mode) {
        Intent intent = new Intent(context, CommonSearchActivity.class);
        intent.putExtra(Constants.IK_SEARCH, mode);
        context.startActivityForResult(intent, Constants.RET_SEARCH);
    }

    public static void start(Activity context, int mode, int extraId) {
        Intent intent = new Intent(context, CommonSearchActivity.class);
        intent.putExtra(Constants.IK_SEARCH, mode);
        intent.putExtra(Constants.IK_EXTRA, extraId);
        context.startActivityForResult(intent, Constants.RET_SEARCH);
    }

    public static void start(Fragment fragment, int mode) {
        Intent intent = new Intent(fragment.getActivity(), CommonSearchActivity.class);
        intent.putExtra(Constants.IK_SEARCH, mode);
        fragment.startActivityForResult(intent, Constants.RET_SEARCH);
    }

    public static void start(Fragment fragment, int mode, int extraId) {
        Intent intent = new Intent(fragment.getActivity(), CommonSearchActivity.class);
        intent.putExtra(Constants.IK_SEARCH, mode);
        intent.putExtra(Constants.IK_EXTRA, extraId);
        fragment.startActivityForResult(intent, Constants.RET_SEARCH);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        searchType = extras.getInt(Constants.IK_SEARCH, MODE_DEFAULT);
        _extraId = extras.getInt(Constants.IK_EXTRA, 0);

    }

    public void ApiSearchVehicle(int status, int page, final PullToRefreshBase refreshView) {
        if (refreshView == null) {
            updateLoadStatus(status);
        }

        Call<SearchDTO> call = HxTransmitRequestHelper.getRequestApi().searchVehicle(_keyword,
                page);
        autoClose(call);
        call.enqueue(new Callback<SearchDTO>() {
            @Override
            public void onResponse(Call<SearchDTO> call, Response<SearchDTO> response) {

                if (response.isSuccessful()) {
                    SearchDTO searchDTO = response.body();
                    if (searchDTO != null && searchDTO.isSuccessful()) {
                        if (refreshView == null) {
                            updateLoadStatus(LOAD_SUCCESS);
                        } else {
                            refreshView.onRefreshComplete();
                        }
                        _pageSize = searchDTO.getPageSize();
                        _mPageNo = searchDTO.getPageNo();

                        if (_mPageNo == 0) {
                            datas.clear();
                        }
                        if (searchDTO.getSiteFeedbackStationList() != null
                                && !searchDTO.getSiteFeedbackStationList().isEmpty()) {
                            datas.addAll(searchDTO.getSiteFeedbackStationList());
                        } else if (searchDTO.getVehicleList() != null
                                && !searchDTO.getVehicleList().isEmpty()) {
                            datas.addAll(searchDTO.getVehicleList());
                        } else {
                            if (_mPageNo == 0) {
                                datas.add(Constants.EMPTY_VIEW);
                            } else {
                                ToastUtil.showToast("无更多数据");
                            }
                        }
                        if (_mPageNo == 0) {
                            myAdapter.notifyDataSetChanged();
                        }

                        return;
                    }
                }
                if (refreshView != null) {
                    updateLoadStatus(LOAD_ERROR);
                } else {
                    refreshView.onRefreshComplete();
                }
            }

            @Override
            public void onFailure(Call<SearchDTO> call, Throwable t) {

                if (refreshView != null) {
                    updateLoadStatus(LOAD_FAILURE);
                } else {
                    refreshView.onRefreshComplete();
                }
            }
        });
    }

    public void ApiSearchStation(final int status, int page, final PullToRefreshBase refreshView) {
        if (refreshView == null) {
            updateLoadStatus(status);
        }
        Call<SearchDTO> call = HxTransmitRequestHelper.getRequestApi().searchStation(_keyword, page);
        autoClose(call);
        call.enqueue(new Callback<SearchDTO>() {
            @Override
            public void onResponse(Call<SearchDTO> call, Response<SearchDTO> response) {

                if (response.isSuccessful()) {
                    SearchDTO searchDTO = response.body();
                    if (searchDTO != null && searchDTO.isSuccessful()) {

                        if (refreshView == null) {
                            updateLoadStatus(LOAD_SUCCESS);
                        } else {
                            refreshView.onRefreshComplete();
                        }
                        _pageSize = searchDTO.getPageSize();
                        _mPageNo = searchDTO.getPageNo();
                        if (_mPageNo == 0) {
                            datas.clear();
                        }
                        if (searchDTO.getSiteFeedbackStationList() != null
                                && !searchDTO.getSiteFeedbackStationList().isEmpty()) {
                            datas.addAll(searchDTO.getSiteFeedbackStationList());
                        } else if (searchDTO.getVehicleList() != null
                                && !searchDTO.getVehicleList().isEmpty()) {
                            datas.addAll(searchDTO.getVehicleList());
                        } else {
                            if (_mPageNo == 0) {
                                datas.add(Constants.EMPTY_VIEW);
                            } else {
                                ToastUtil.showToast("无更多数据");
                            }
                        }
                        if (_mPageNo == 0) {
                            myAdapter.notifyDataSetChanged();
                        }
                        return;
                    }
                }

                if (refreshView == null) {
                    updateLoadStatus(LOAD_ERROR);
                } else {
                    refreshView.onRefreshComplete();
                }

            }

            @Override
            public void onFailure(Call<SearchDTO> call, Throwable t) {
                if (refreshView != null) {
                    updateLoadStatus(LOAD_FAILURE);
                } else {
                    // refreshView.onRefreshComplete();
                }
            }
        });
    }


    @Override
    public void initView() {
        super.initView();
        setSupportActionBar(toolbar);
        myAdapter = new MyAdapter();

        toolbar.setListener(new StaticSearchBar.SearchListener() {
            @Override
            public void doSearch(String keyword) {
                _keyword = keyword;
                if (searchType == MODE_SEARCH_PLATE) {
                    ApiSearchVehicle(LOADING, 0, null);
                } else if (searchType == MODE_SEARCH_STATION) {
                    ApiSearchStation(LOADING, 0, null);
                }
            }

            @Override
            public void cancel() {
                finish();
            }
        });

        pullView.setHeaderLayout(new CustomHeaderLayout(this));
        pullView.setFooterLayout(new CustomFooterLayout(this));
        pullView.setOnRefreshListener(this);
        listView = pullView.getRefreshableView();
        listView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));
        //        list.addItemDecoration(
        //                new DividerDecoration(ContextCompat.getDrawable(this, R.drawable.line_h_12dp),
        //                        LinearLayoutManager.VERTICAL));
        listView.setAdapter(myAdapter);
    }

    @Override
    public void requestData() {
        if (searchType == MODE_SEARCH_PLATE) {
            ApiSearchVehicle(LOADING, 0, null);
        } else if (searchType == MODE_SEARCH_STATION) {
            ApiSearchStation(LOADING, 0, null);
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        if (searchType == MODE_SEARCH_PLATE) {
            ApiSearchVehicle(LOADING, 0, refreshView);
        } else if (searchType == MODE_SEARCH_STATION) {
            ApiSearchStation(LOADING, 0, refreshView);
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        if (searchType == MODE_SEARCH_PLATE) {
            ApiSearchVehicle(LOADING, _mPageNo + 1, refreshView);
        } else if (searchType == MODE_SEARCH_STATION) {
            ApiSearchStation(LOADING, _mPageNo + 1, refreshView);
        }
    }


    protected class MyAdapter extends RecyclerView.Adapter {

        private static final int ITEM_EMPTY        = 0x00;
        private static final int ITEM_TYPE_STATION = 0x01;
        private static final int ITEM_TYPE_PLATE   = 0x02;


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == ITEM_TYPE_STATION) {
                return new StationHolder(mInflater.inflate(R.layout.item_station, parent, false));
            } else if (viewType == ITEM_TYPE_PLATE) {
                return new PlateHolder(mInflater.inflate(R.layout.item_vehicle, parent, false));
            } else if (viewType == ITEM_EMPTY) {
                return new EmptyHolder(mInflater.inflate(R.layout.item_empty_face_top2, parent, false));
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == ITEM_TYPE_STATION) {
                ((StationHolder) holder).update(position);
            } else if (getItemViewType(position) == ITEM_TYPE_PLATE) {
                ((PlateHolder) holder).update(position);
            } else if (getItemViewType(position) == ITEM_EMPTY) {
                ((EmptyHolder) holder).update(position);
            }

        }

        @Override
        public int getItemViewType(int position) {
            Object data = datas.get(position);
            if (data instanceof StationDTO) {
                return ITEM_TYPE_STATION;
            } else if (data instanceof VehicleDTO) {
                return ITEM_TYPE_PLATE;
            }
            return ITEM_EMPTY;
        }

        @Override
        public int getItemCount() {
            return datas == null ? 0 : datas.size();
        }


        protected class PlateHolder extends RecyclerView.ViewHolder implements View
                .OnClickListener {
            @BindView(R.id.img)
            ImageView img;
            @BindView(R.id.tv_plate_no)
            TextView  tvPlateNo;
            @BindView(R.id.tv_model)
            TextView  tvModel;
            @BindView(R.id.tv_is_use)
            TextView  tvIsUse;
            @BindView(R.id.dv_top)
            View      dvTop;

            int  position;
            View itemView;

            public PlateHolder(View itemView) {
                super(itemView);
                this.itemView = itemView;
                ButterKnife.bind(this, itemView);
            }


            public void update(int position) {
                this.position = position;
                dvTop.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
                if (datas.get(position) instanceof VehicleDTO) {
                    VehicleDTO data = (VehicleDTO) datas.get(position);
                    loadText(tvPlateNo, data.getLicensePlateNum());
                    loadText("型号：", tvModel, data.getVehicleModel(), "暂无");
                    if (data.getIsUse() == 0) {
                        tvIsUse.setText("未使用");
                        tvIsUse.setTextColor(ContextCompat.getColor(CommonSearchActivity.this, R
                                .color.state_green));
                    } else {
                        tvIsUse.setText("已使用");
                        tvIsUse.setTextColor(ContextCompat.getColor(CommonSearchActivity.this, R
                                .color.state_orange));
                    }
                    itemView.setOnClickListener(this);
                }
            }

            @Override
            public void onClick(View v) {
                if (datas.get(position) instanceof VehicleDTO) {
                    toolbar.hideIme();
                    final VehicleDTO data = (VehicleDTO) datas.get(position);
                    if (data.getIsUse() == 1) {
                        ToastUtil.showToast("无法绑定使用中的车辆！");
                        return;
                    }
                    Dialog confirmDialog = DialogUtil.getConfirmDialog(CommonSearchActivity.this,
                            "确认绑定车辆:" + data.getLicensePlateNum(), new DialogInterface
                                    .OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ApiAddVehicle(data.getLicensePlateNum(), data.getVehicleModel());

                                }
                            }).show();

                }
            }
        }


        class StationHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            @BindView(R.id.img)
            ImageView   img;
            @BindView(R.id.rl_img)
            RoundLayout rlImg;
            @BindView(R.id.stationName)
            TextView    stationName;
            @BindView(R.id.buildAddress)
            TextView    buildAddress;
            @BindView(R.id.ownerName)
            TextView    ownerName;
            @BindView(R.id.phone)
            TextView    phone;
            @BindView(R.id.state)
            TextView    state;
            @BindView(R.id.dv_top)
            View        dvTop;
            @BindColor(R.color.state_green)
            int         static_normal;
            @BindColor(R.color.state_orange)
            int         static_bug;
            @BindColor(R.color.state_gray)
            int         static_out;
            View itemView;
            int  position;

            public StationHolder(View itemView) {
                super(itemView);
                this.itemView = itemView;
                ButterKnife.bind(this, itemView);

            }

            public void update(int position) {
                this.position = position;
                dvTop.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
                if (datas.get(position) instanceof StationDTO) {
                    StationDTO data = (StationDTO) datas.get(position);
                    setStateText(state, data.getStationState());
                    Log.d("Zoes", "" + data.getStationImg());
                    loadNetImg(img, data.getStationImg());

                    loadText(stationName, data.getStationName());
                    loadText("地址：", buildAddress, data.getAddress(), "暂无");
                    loadText("负责人：", ownerName, data.getContactPerson(), "暂无");
                    loadText(phone, data.getContactPhone());
                    itemView.setOnClickListener(this);
                }
            }

            private void setStateText(TextView textView, int state) {
                //站点状态 0:正常，1：通讯超时，2、故障，3、待初始化
                textView.setVisibility(View.VISIBLE);
                switch (state) {
                    case 0:
                        textView.setText("正常");
                        textView.setTextColor(static_normal);
                        textView.setBackgroundResource(R.drawable.bg_normal_green);
                        //                        SDKBug.setBackgroundResourceWithPadding(textView,R.drawable.bg_normal_green);
                        break;
                    case 1:
                        textView.setText("超时");
                        textView.setTextColor(static_bug);
                        textView.setBackgroundResource(R.drawable.bg_bug);

                        break;
                    case 2:
                        textView.setText("故障");
                        textView.setTextColor(static_bug);
                        textView.setBackgroundResource(R.drawable.bg_bug);
                        break;
                    case 3:
                        textView.setText("待初始化");
                        textView.setTextColor(static_bug);
                        textView.setBackgroundResource(R.drawable.bg_bug);

                        break;
                    default:
                        textView.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onClick(View v) {

                if (datas.get(position) instanceof StationDTO) {
                    Log.d("Zoes", "click" + position);
                    StationDTO data = (StationDTO) datas.get(position);
                    Intent intent = new Intent();
                    intent.putExtra(Constants.IK_STATION_CODE, data.getStationCode());
                    intent.putExtra(Constants.IK_STATION_NAME, data.getStationName());
                    setResult(Activity.RESULT_OK, intent);
                    toolbar.hideIme();
                    finish();
                }

            }

        }


        public class EmptyHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_tip)
            TextView tvTip;
            View itemView;

            public EmptyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
                //ImageMarkUtil.setWaterMarkTextBg(itemView,CommonSearchActivity.this,"暂无数据");
            }

            public void update(int position) {
                tvTip.setText("暂无相关结果！");

            }
        }

    }

    private void ApiAddVehicle(final String licensePlateNum, final String vehicleModel) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().addVehicle(licensePlateNum, _extraId);
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful() && baseDTO != null) {
                    if (baseDTO.isSuccessful()) {
                        updateLoadStatus(LOAD_SUCCESS);
                        Intent intent = new Intent();
                        intent.putExtra(Constants.IK_PLATE_NUM, licensePlateNum);
                        intent.putExtra(Constants.IK_VEHICLE_MODEL, vehicleModel);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                        return;
                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast("数据错误");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                ToastUtil.showToast("网络故障");
            }
        });

    }


}
